package four;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.LongStream;

/**
 * @Auther : yxpweb
 * @Date : 2021/7/2 12:19
 * @Description: 求和计算的任务 ForkJoin /   stream并行流
 */
public class ForkJoinDemo {
    public static void main(String[] args) {
        long start = 0L;
        long end = 10_0000_0000;

        test1(start, end);
        test2(start, end);
        test3(start, end);
    }

    public static void test1(long start, long end) {
        long sum = 0;
        long startTime = System.currentTimeMillis();
        for (long i = start; i <= end; i++) {
            sum += i;
        }
        long endTime = System.currentTimeMillis();
        System.out.println("time1 = " + (startTime - endTime) + " sum= " + sum);
    }

    public static void test2(long start, long end) {
        long startTime = System.currentTimeMillis();

        ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
        ForkJoinTask<Long> submit = forkJoinPool.submit(new MyForkJoinTask(start, end));
        Long sum = null;
        try {
            sum = submit.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("time2 = " + (startTime - endTime) + " sum= " + sum);
    }

    public static void test3(long start, long end) {
        long startTime = System.currentTimeMillis();
        long sum = LongStream.rangeClosed(start, end).parallel().reduce(0, Long::sum);
        long endTime = System.currentTimeMillis();
        System.out.println("time3 = " + (startTime - endTime) + " sum= " + sum);
    }
}

class MyForkJoinTask extends RecursiveTask<Long> {

    private long start;
    private long end;

    private long mid = 10000;

    public MyForkJoinTask(long start, long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {

        if ((start - end) < mid) {
            long sum = 0L;
            for (long i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        } else {
            long mid = (start + end) / 2;
            MyForkJoinTask task1 = new MyForkJoinTask(start, mid);
            task1.fork();
            MyForkJoinTask task2 = new MyForkJoinTask(mid + 1, end);
            task2.fork();

            return task1.join() + task2.join();
        }
    }
}
